<template>
  <div class="notification-center">
    <div class="page-header">
      <div class="header-left">
        <el-button
          :icon="ArrowLeft"
          circle
          @click="handleBack"
          class="back-button"
        />
        <div class="header-title">
          <h1>通知中心</h1>
          <p>查看和管理您的所有通知</p>
        </div>
      </div>
      <div class="header-actions">
        <el-button
          v-if="unreadCount > 0"
          type="primary"
          :icon="Check"
          @click="handleMarkAllRead"
        >
          全部已读
        </el-button>
      </div>
    </div>

    <el-card class="list-view-card" shadow="never">
      <div class="table-header">
        <div class="title">
          <strong>通知列表</strong>
          <span class="count">共 {{ total }} 条</span>
        </div>
        <div class="header-actions">
          <el-radio-group v-model="filterType" @change="handleFilterChange" size="small">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="unread">未读</el-radio-button>
            <el-radio-button label="read">已读</el-radio-button>
          </el-radio-group>
          <span v-if="unreadCount > 0" class="unread-badge">未读 {{ unreadCount }} 条</span>
        </div>
      </div>

      <div v-loading="loading" class="notification-list-container">
        <el-empty
          v-if="!loading && notifications.length === 0"
          description="暂无通知"
          :image-size="120"
        />

        <div v-else-if="!loading && notifications.length > 0" class="notification-list">
          <div
            v-for="notification in notifications"
            :key="notification.id"
            class="notification-item"
            :class="{ 'is-unread': !notification.is_read }"
            @click="handleNotificationClick(notification)"
          >
            <div class="notification-icon">
              <el-icon :size="24" :color="getNotificationIconColor(notification.type)">
                <component :is="getNotificationIcon(notification.type)" />
              </el-icon>
            </div>
            <div class="notification-content">
              <div class="notification-header">
                <span class="notification-title">{{ notification.title }}</span>
                <span class="notification-time">{{ formatTime(notification.created_at) }}</span>
              </div>
              <div class="notification-body">
                <div class="notification-body-content">
                  <UserDisplay
                    v-if="notification.metadata?.operator_id"
                    :user-id="notification.metadata.operator_id"
                    :user-name="notification.metadata.operator_name"
                    :user-avatar="notification.metadata.operator_avatar"
                    :size="'small'"
                    class="notification-operator"
                  />
                  <span class="notification-text">{{ getNotificationText(notification) }}</span>
                </div>
              </div>
              <div v-if="notification.related_type && notification.related_id" class="notification-related">
                <el-tag size="small" type="info">
                  {{ getRelatedTypeLabel(notification.related_type) }}
                </el-tag>
              </div>
            </div>
            <div class="notification-actions">
              <el-button
                v-if="!notification.is_read"
                type="text"
                size="small"
                :icon="Check"
                @click.stop="handleMarkRead(notification.id)"
              >
                标记已读
              </el-button>
              <el-button
                type="text"
                size="small"
                :icon="Delete"
                @click.stop="handleDelete(notification.id)"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <div class="table-footer">
        <div class="table-pagination">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Check,
  Delete,
  Bell,
  Document,
  Folder,
  User,
  ChatDotRound,
  Warning,
  ArrowLeft
} from '@element-plus/icons-vue'
import { useNotificationStore } from '@/stores/notification'
import type { Notification } from '@/types/notification'
import { NotificationType, RelatedObjectType } from '@/types/notification'
import UserDisplay from '@/components/ui/UserDisplay.vue'

const router = useRouter()
const notificationStore = useNotificationStore()

const filterType = ref<'all' | 'unread' | 'read'>('all')

// 使用 store 中的分页状态
const notifications = computed(() => notificationStore.notifications)
const unreadCount = computed(() => notificationStore.unreadCount)
const total = computed(() => notificationStore.total)
const loading = computed(() => notificationStore.loading)
const currentPage = computed(() => notificationStore.currentPage)
const pageSize = computed(() => notificationStore.pageSize)

// 获取通知图标
const getNotificationIcon = (type: string) => {
  const iconMap: Record<string, any> = {
    [NotificationType.TASK_ASSIGNED]: Document,
    [NotificationType.TASK_COMPLETED]: Check,
    [NotificationType.TASK_STATUS_CHANGED]: Document,
    [NotificationType.TASK_UPDATED]: Document,
    [NotificationType.TASK_DEADLINE_REMINDER]: Warning,
    [NotificationType.PROJECT_UPDATED]: Folder,
    [NotificationType.PROJECT_MEMBER_ADDED]: User,
    [NotificationType.COMMENT_ADDED]: ChatDotRound,
    [NotificationType.REQUIREMENT_UPDATED]: Document,
    [NotificationType.VERSION_UPDATED]: Document,
    [NotificationType.DEFECT_CREATED]: Warning,
    [NotificationType.DEFECT_UPDATED]: Document,
    [NotificationType.DEFECT_DELETED]: Delete
  }
  return iconMap[type] || Bell
}

// 获取通知图标颜色
const getNotificationIconColor = (type: string) => {
  const colorMap: Record<string, string> = {
    [NotificationType.TASK_ASSIGNED]: '#409EFF',
    [NotificationType.TASK_COMPLETED]: '#67C23A',
    [NotificationType.TASK_STATUS_CHANGED]: '#E6A23C',
    [NotificationType.TASK_UPDATED]: '#409EFF',
    [NotificationType.TASK_DEADLINE_REMINDER]: '#F56C6C',
    [NotificationType.PROJECT_UPDATED]: '#409EFF',
    [NotificationType.PROJECT_MEMBER_ADDED]: '#67C23A',
    [NotificationType.COMMENT_ADDED]: '#909399',
    [NotificationType.REQUIREMENT_UPDATED]: '#409EFF',
    [NotificationType.VERSION_UPDATED]: '#409EFF',
    [NotificationType.DEFECT_CREATED]: '#F56C6C',
    [NotificationType.DEFECT_UPDATED]: '#E6A23C',
    [NotificationType.DEFECT_DELETED]: '#909399'
  }
  return colorMap[type] || '#909399'
}

// 获取关联类型标签
const getRelatedTypeLabel = (type: string) => {
  const labelMap: Record<string, string> = {
    [RelatedObjectType.TASK]: '任务',
    [RelatedObjectType.PROJECT]: '项目',
    [RelatedObjectType.REQUIREMENT]: '需求',
    [RelatedObjectType.VERSION]: '版本',
    [RelatedObjectType.COMMENT]: '评论',
    [RelatedObjectType.DEFECT]: '缺陷',
    [RelatedObjectType.TEST_CASE]: '测试用例'
  }
  return labelMap[type] || type
}

// 获取通知文本（去除用户名部分）
const getNotificationText = (notification: Notification) => {
  const content = notification.content || ''
  const operatorName = notification.metadata?.operator_name
  
  if (operatorName && content.startsWith(operatorName + ' ')) {
    // 如果内容以操作者姓名开头，移除姓名部分
    return content.substring(operatorName.length + 1)
  }
  
  return content
}

// 格式化时间
const formatTime = (time: string) => {
  const date = new Date(time)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)

  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 筛选变化
const handleFilterChange = () => {
  notificationStore.setPage(1)
  fetchNotifications()
}

// 获取通知列表
const fetchNotifications = async () => {
  const params: any = {
    page: notificationStore.currentPage,
    limit: notificationStore.pageSize
  }

  if (filterType.value === 'unread') {
    params.is_read = false
  } else if (filterType.value === 'read') {
    params.is_read = true
  }

  await notificationStore.fetchNotifications(params)
}

// 页面变化
const handlePageChange = async (page: number) => {
  notificationStore.setPage(page)
  await fetchNotifications()
}

// 每页数量变化
const handleSizeChange = async (size: number) => {
  notificationStore.setPageSize(size)
  notificationStore.setPage(1)
  await fetchNotifications()
}

// 处理通知点击
const handleNotificationClick = async (notification: Notification) => {
  // 如果未读，标记为已读
  if (!notification.is_read) {
    await handleMarkRead(notification.id)
  }

  // 跳转到相关页面
  if (notification.related_type && notification.related_id) {
    if (notification.related_type === RelatedObjectType.TASK) {
      router.push(`/tasks/${notification.related_id}`)
    } else if (notification.related_type === RelatedObjectType.PROJECT) {
      router.push(`/projects/${notification.related_id}`)
    }
  }
}

// 标记为已读
const handleMarkRead = async (notificationId: string) => {
  try {
    await notificationStore.markAsRead(notificationId)
  } catch (error) {
    ElMessage.error('标记已读失败')
  }
}

// 标记全部为已读
const handleMarkAllRead = async () => {
  try {
    await notificationStore.markAllAsRead()
    ElMessage.success('已标记全部为已读')
    await fetchNotifications()
  } catch (error) {
    ElMessage.error('标记全部已读失败')
  }
}

// 返回上一页
const handleBack = () => {
  router.back()
}

// 删除通知
const handleDelete = async (notificationId: string) => {
  try {
    await ElMessageBox.confirm('确定要删除这条通知吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await notificationStore.removeNotification(notificationId)
    ElMessage.success('删除成功')
    await fetchNotifications()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 组件挂载
onMounted(async () => {
  // 初始化分页状态
  notificationStore.setPage(1)
  notificationStore.setPageSize(20)
  await fetchNotifications()
  // 获取未读数量
  await notificationStore.fetchUnreadCount()
  // 连接 SSE 实时推送
  notificationStore.connectStream()
})

// 组件卸载
onUnmounted(() => {
  // 断开 SSE 连接
  notificationStore.disconnectStream()
})
</script>

<style scoped lang="scss">
.notification-center {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;

      .back-button {
        flex-shrink: 0;
      }

      .header-title {
        h1 {
          margin: 0 0 8px 0;
          font-size: 24px;
          font-weight: 600;
        }

        p {
          margin: 0;
          color: var(--el-text-color-secondary);
        }
      }
    }
  }

  .list-view-card {
    display: flex;
    flex-direction: column;
    height: calc(100vh - 140px);
    min-height: 600px;
    max-height: 900px;

    :deep(.el-card__body) {
      display: flex;
      flex-direction: column;
      flex: 1;
      min-height: 0;
      overflow: hidden;
      padding: 0;
    }
  }

  .table-header {
    padding: 16px 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #ebeef5;
    background: #fafbfc;
    flex-shrink: 0;

    .title {
      display: flex;
      align-items: center;
      gap: 12px;

      strong {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }

      .count {
        font-size: 14px;
        color: #909399;
        font-weight: 400;
      }
    }

    .header-actions {
      display: flex;
      align-items: center;
      gap: 16px;

      .unread-badge {
        padding: 4px 12px;
        background: #ecf5ff;
        color: #409eff;
        border-radius: 12px;
        font-size: 13px;
        font-weight: 500;
      }
    }
  }

  .notification-list-container {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .el-empty {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      flex: 1;
      min-height: 400px;
      padding: 40px 20px;
    }

    .notification-list {
      flex: 1;
      min-height: 0;
      overflow-y: auto;
      overflow-x: hidden;
      
      &::-webkit-scrollbar {
        width: 8px;
      }
      
      &::-webkit-scrollbar-track {
        background: var(--el-fill-color-lighter);
        border-radius: 4px;
      }
      
      &::-webkit-scrollbar-thumb {
        background: var(--el-border-color-darker);
        border-radius: 4px;
        
        &:hover {
          background: var(--el-border-color);
        }
      }

      .notification-item {
        display: flex;
        padding: 16px 24px;
        border-bottom: 1px solid #ebeef5;
        cursor: pointer;
        transition: background-color 0.2s;

        &:hover {
          background-color: #f5f7fa;
        }

        &.is-unread {
          background-color: #ecf5ff;
          border-left: 3px solid #409eff;
        }

        .notification-icon {
          margin-right: 16px;
          flex-shrink: 0;
        }

        .notification-content {
          flex: 1;
          min-width: 0;

          .notification-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;

            .notification-title {
              font-size: 16px;
              font-weight: 600;
              color: var(--el-text-color-primary);
            }

            .notification-time {
              font-size: 12px;
              color: var(--el-text-color-secondary);
            }
          }

          .notification-body {
            font-size: 14px;
            color: var(--el-text-color-regular);
            line-height: 1.6;
            margin-bottom: 8px;

            .notification-body-content {
              display: flex;
              align-items: center;
              gap: 8px;
              flex-wrap: wrap;

              .notification-operator {
                flex-shrink: 0;
              }

              .notification-text {
                flex: 1;
                min-width: 0;
              }
            }
          }

          .notification-related {
            margin-top: 8px;
          }
        }

        .notification-actions {
          display: flex;
          flex-direction: column;
          gap: 8px;
          margin-left: 16px;
          flex-shrink: 0;
        }
      }
    }
  }

  .table-footer {
    padding: 16px 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-top: 1px solid #ebeef5;
    background: #fafbfc;
    flex-shrink: 0;
    min-height: 60px;
    position: relative;
  }

  .table-pagination {
    margin-left: auto;
    
    :deep(.el-pagination) {
      margin: 0;
      
      .el-pagination__total {
        color: #606266;
        font-size: 13px;
        font-weight: 500;
        margin-right: 12px;
      }
      
      .el-pagination__sizes {
        margin-right: 12px;
        
        .el-select {
          .el-input__inner {
            height: 28px;
            line-height: 28px;
            font-size: 13px;
            border-radius: 4px;
            border-color: #dcdfe6;
            transition: all 0.2s;
            
            &:hover {
              border-color: #c0c4cc;
            }
          }
          
          &.is-focus .el-input__inner {
            border-color: #409eff;
          }
        }
      }
      
      .btn-prev,
      .btn-next {
        width: 28px;
        height: 28px;
        line-height: 28px;
        border-radius: 4px;
        border: 1px solid #dcdfe6;
        background: #ffffff;
        color: #606266;
        font-size: 14px;
        transition: all 0.2s;
        
        &:hover:not(.disabled) {
          color: #409eff;
          border-color: #409eff;
          background: #ecf5ff;
        }
        
        &.disabled {
          color: #c0c4cc;
          cursor: not-allowed;
          background: #f5f7fa;
        }
      }
      
      .el-pager {
        margin: 0 8px;
        
        li {
          min-width: 28px;
          height: 28px;
          line-height: 28px;
          border-radius: 4px;
          border: 1px solid #dcdfe6;
          background: #ffffff;
          color: #606266;
          font-size: 13px;
          font-weight: 500;
          margin: 0 2px;
          transition: all 0.2s;
          
          &:hover:not(.disabled):not(.is-active) {
            color: #409eff;
            border-color: #409eff;
            background: #ecf5ff;
          }
          
          &.is-active {
            color: #ffffff;
            background: #409eff;
            border-color: #409eff;
            font-weight: 600;
          }
          
          &.disabled {
            color: #c0c4cc;
            cursor: not-allowed;
            background: #f5f7fa;
          }
        }
      }
      
      @media (max-width: 768px) {
        .el-pagination__total {
          display: none;
        }
      }
    }
  }
}
</style>

